package com.lambert.young.im.handler;

import com.alibaba.fastjson2.JSON;
import com.lambert.young.im.IMServer;
import com.lambert.young.im.command.ChatMessage;
import com.lambert.young.im.command.Result;
import com.lambert.young.im.command.ResultType;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

/**
 * <p>TODO </p>
 *
 * @author liubaolin
 * @since 2024/11/1 10:58 AM
 */
public class ChatHandler {
    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame){
        try{
            ChatMessage chat = JSON.parseObject(frame.text(),ChatMessage.class);
            if (StringUtil.isNullOrEmpty(chat.getTarget())){
                ctx.channel().writeAndFlush(Result.fail(ResultType.NOT_FIND_TARGET.getMessage()));
                return;
            }
            Object channel = IMServer.USERS.get(chat.getTarget());
            if (channel instanceof Channel privateChannel){
                if (null == privateChannel || !privateChannel.isActive()){
                    ctx.channel().writeAndFlush(Result.fail("消息发送失败，对方" + chat.getTarget() + "不在线"));
                }else{
                    privateChannel.writeAndFlush(Result.success(chat.getNickName(),chat.getContent()));
                }
            }
            if (channel instanceof ChannelGroup groupChannel){
                groupChannel.writeAndFlush(Result.success("系统群消息","{\"nickname\":\""+chat.getNickName()+"\",\"message\":\""+chat.getContent().replace("\n","")+"\"}"));
            }
        }catch (Exception e){
            ctx.channel().writeAndFlush(Result.fail(ResultType.MESSAGE_FORMAT_ERROR.getMessage()));
        }
    }
}
